import { computed, onMounted, onUnmounted, provide, reactive, ref, watch } from 'vue'
import {
  getLVTHistoryData,
  getLVTRealTimeData,
  getLVTSumData,
  getLVTTabulateData,
  dicItemByCode,
  sameDayProductionLineCode
} from '@/api/mesApi'
import config from '@/config/index'
import { useI18n } from 'vue-i18n'

let task = null

const killTask = () => {
  if (task) {
    clearInterval(task)
  }
}
const today = new Date();

// 获取当前月份的第一天
const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

// 获取当前月份的最后一天
const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);

const createData = async (remoteData, queryParams) => {
  remoteData.value.ready = true
  const {
    productionLineCode,
    shiftCode,
    mesProduceDate,
    mesProduceDate1
  } = queryParams

  /* 1.LVT单线别历史数据 */
  if (!queryParams.productionLineCode) {
    remoteData.value.historyData = []
    return
  }

  await getLVTHistoryData({
    productionLineCode: queryParams.productionLineCode,
    shiftCode: queryParams.shiftCode?queryParams.shiftCode:'ALL',
    mesProduceDate: queryParams.mesProduceDate?queryParams.mesProduceDate:firstDayOfMonth.toISOString().split('T')[0],
    mesProduceDate1: queryParams.mesProduceDate1?queryParams.mesProduceDate1:lastDayOfMonth.toISOString().split('T')[0],
    processCode: 'LVT',
    current: queryParams.page,
    size: queryParams.rows
  }).then((res) => {
    if (res.code === 0) {
      remoteData.value.historyData = [...res.data.records]
    } else {
      remoteData.value.historyData = []
    }
    queryParams.total = res.data.total
  }
  )
  /* 2.获取挤出汇总数据 */
  await getLVTTabulateData({
    shiftCode,
    mesProduceDate,
    mesProduceDate1
  }).then(function (res) {
    if (res) {
      for (const item of remoteData.value.processCount) {
        item.value = res.data?.[item.field] || 0
      }
    }
  }, function (e) {
    console.error(e)
  })
  /* 3.获取挤出单条线汇总数据 */
  await getLVTSumData({
    productionLineCode,
    shiftCode:queryParams.shiftCode?queryParams.shiftCode:'ALL',
    processCode: 'LVT',
  }).then(function (res) {
    if (res) {
      const value = remoteData.value.processCount[0].value || 0
      const value1 = remoteData.value.processCount[1].value || 0
      const value2 = remoteData.value.processCount[2].value || 0
      const value3 = remoteData.value.processCount[3].value || 0
      const sumQtyPer = (value ? (res.data.sumqty || 0) / value : 0).toFixed(3)
      const totalOutputNumPer = (value1 ? (res.data.totalOutputNum || 0) / value1 : 0).toFixed(3)
      const standardBuckleQuantityPer = (value2 ? (res.data.standardBuckleQuantity || 0) / value2 : 0).toFixed(3)
      // 总产出片数 总产出托数 总标准扣料量 总投料量
      remoteData.value.lineCount = {
        sumQty: res.data.sumqty || 0,
        totalOutputNum: res.data.totalOutputNum || 0,
        standardBuckleQuantity: res.data.standardBuckleQuantity || 0,
        // sumBuckleQty: res.data.sumBuckleQty || 0,
        sumQtyPer: sumQtyPer,
        totalOutputNumPer: totalOutputNumPer,
        standardBuckleQuantityPer,
        // sumBuckleQtyPer
      }
    }
  }, function (e) {
    console.error(e)
  })
  /* 4.获取基础单条线实时数据 */
  await getLVTRealTimeData({ productionLineCode }).then(function (res) {
    remoteData.value.realTimeData = res.data
  })
  /* 5.查询工序当天正在生产的产线 */
  sameDayProductionLineCode({
    processCode: 'LVT',
  }).then(function (res) {
    remoteData.value.currentProductionLine = res.data
  })
  /* 6.数据字典获取LVT条线自动刷新的频率 */
  dicItemByCode({ code: 'LVTVIEW' }).then(function (res) {
    remoteData.value.refreshFrequency = res.data
  })
}

const dataReady = (remoteData, once, queryParams) => {
  createData(remoteData, queryParams)
  if (!once && !task) {
    task = setInterval(async () => {
      await createData(remoteData, queryParams)
    }, 5000)
  }
}

/**
 * 获取LVT工序的相关数据
 * @returns {{remoteData: UnwrapNestedRefs<{ready: boolean, processLine: *[]}>}}
 */
export function getLVTData(queryParams, once) {
  const { t } = useI18n()
  const span = 4
  /* 设置对象数组的模板 */
  const processArr = [
    {
      name: t('wms.totalOofPieces'),
      field: 'sumQty',
      icon: config.ossUrl + '/afl-data-screen/images/icon-all-input.png',
      value: 0,
      span: span,
      unit: 'pcs'
    },
    {
      name: t('wms.totalOutputTosses'),
      field: 'totalOutputNum',
      icon: config.ossUrl + '/afl-data-screen/images/icon-output.png',
      value: 0,
      span: span,
      unit: 'plt'
    },
    {
      name: t('wms.standardBuckleQuantity'),
      field: 'standardBuckleQuantity',
      icon: config.ossUrl + '/afl-data-screen/images/icon-input.png',
      value: 0,
      span: span,
      unit: 'kg'
    },
    {
      name: t('mes.totalFeedVolume'),
      field: 'sumBuckleQty',
      icon: config.ossUrl + '/afl-data-screen/images/icon-takeOut.png',
      value: 0,
      span: span,
      unit: 'kg'
    }
  ]
  // eslint-disable-next-line
  const remoteData = ref({
    ready: false,
    historyData: {},
    realTimeData: {},
    lineCount: {},
    processCount: JSON.parse(JSON.stringify(processArr)),
    refreshFrequency: [], // 刷新频率
    currentProductionLine: [] // 当前生产工序产线
  })
  /* 挂在操作 */
  onMounted(() => dataReady(remoteData, once, queryParams))
  onUnmounted(killTask)

  /* 监听操作 */
  watch(() => queryParams, () => {
    // console.log('查询参数发生变化', queryParams)
    dataReady(remoteData, true, queryParams)
  }, { deep: true })

  return { remoteData }
}
